﻿Imports LiteDB

Public Class AppSettings
    Private mItems As List(Of AppSettingsItem)
#Region "Get Properties"
    ReadOnly Property GetItem(SettingsID As Integer) As AppSettingsItem
        Get
            Return (From x In mItems Where x.SettingsID = SettingsID).First
        End Get
    End Property
    ReadOnly Property SettingsList() As List(Of AppSettingsItem)
        Get
            Return mItems
        End Get
    End Property
    ReadOnly Property GetNextID As Integer
        Get
            If mItems.Count = 0 Then Return 1
            Return (From x In mItems Select x.ID).Max + 1
        End Get
    End Property
#End Region
    Sub New()
        mItems = New List(Of AppSettingsItem)
        LoadList()
    End Sub
    Private Sub LoadList()
        Using db As New LiteEngine(gApp.DatabaseFile)
            mItems = (From x In db.GetCollection(Of AppSettingsItem)(DTSettings).All Where x.ApplicationID = gUDApp.SelectedAppID Order By x.ID).ToList
        End Using
    End Sub
    Function Save(Data As AppSettingsItem) As Integer
        Dim tAdd As Boolean
        Dim tNewID As Integer
        Dim n As AppSettingsItem
        Using db As New LiteEngine(gApp.DatabaseFile)
            Dim col = db.GetCollection(Of AppSettingsItem)(DTSettings)

            tAdd = False
            If Data.SettingsID = 0 Then
                Try
                    tNewID = (From x In col.All Select x.SettingsID).Max + 1
                Catch ex As Exception
                    tNewID = 1
                End Try
                Data.SettingsID = tNewID
                tAdd = True
            End If

            If tAdd = False Then
                n = col.FindById(Data.SettingsID)
                Dim a = (From x In mItems Where x.SettingsID = Data.SettingsID).First
                mItems.Remove(a)
            Else
                n = New AppSettingsItem
                n.SettingsID = Data.SettingsID
            End If

            n.ApplicationID = Data.ApplicationID
            n.ID = Data.ID
            n.Description = Data.Description
            n.Value = Data.Value
            n.StatusID = Data.StatusID

            If tAdd = True Then
                col.Insert(n)
            Else
                col.Update(n)
            End If
            mItems.Add(n)
        End Using
        Return n.ApplicationID
    End Function
    Function CheckIDExists(ID As Integer) As Boolean
        Dim a = From x In mItems Where x.ID = ID
        If a.Count > 0 Then Return True
        Return False
    End Function
End Class
